<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-button type="primary" style="margin-bottom: 20px;" @click="addMode">添加工作模式</el-button>
      <!-- 表格区域 -->
      <div class="table-container">
        <el-table
          v-loading="isLoading"
          :data="tableData"
          stripe
          style="width: 100%"
          class="custom-table"
        >
          <el-table-column
            fixed
            prop="id"
            label="工作模式编号"
          />
          <el-table-column
            prop="name"
            label="工作模式"
          />
          <el-table-column
            prop="workPatternTypeDesc"
            label="类型"
          />
          <el-table-column
            prop="workDate"
            label="工作日期"
          />
          <el-table-column
            prop="workStartMinute1"
            label="工作时间"
          >
            <template v-slot="{row}">
              <span>{{ workTime(row.workStartMinute1,row.workEndMinute1) }}小时</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
          >
            <template v-slot="{row}">
              <el-button type="text" size="small" @click="editFn(row.id)">编辑</el-button>
              <el-button type="text" size="small" @click="delFn(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <el-row style="height: 60px; margin-top: 20px;" type="flex" justify="center">
        <el-pagination
          :current-page="params.page"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="params.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="counts"
          @size-change="changePageSize"
          @current-change="changePage"
        />
      </el-row>
    </el-card>
    <!-- 弹窗dialog -->
    <el-dialog :title="showtitle" :visible="isShow" @close="closeFn">
      <el-tabs v-model="activeName">
        <el-tab-pane v-if="isWeek" label="礼拜制" name="1">
          <el-form ref="form" :model="form" label-width="130px" :rules="rules">
            <el-form-item label="工作模式名称" prop="name">
              <el-input v-model="form.name" autocomplete="off" />
            </el-form-item>
            <el-form-item label="连续工作天数" prop="day">
              <el-checkbox-group v-model="selectedDays">
                <el-checkbox :label="1">周一</el-checkbox>
                <el-checkbox :label="2">周二</el-checkbox>
                <el-checkbox :label="3">周三</el-checkbox>
                <el-checkbox :label="4">周四</el-checkbox>
                <el-checkbox :label="5">周五</el-checkbox>
                <el-checkbox :label="6">周六</el-checkbox>
                <el-checkbox :label="7">周日</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <div class="tips">选中为工作时间，未选中为休息时间</div>
            <el-form-item label="工作时间" required prop="time">
              <el-col :span="11">
                <el-time-picker
                  v-model="form.workStartMinute1"
                  is-range
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  placeholder="选择时间范围"
                  format="HH:mm"
                  value-format="HH:mm"
                  :picker-options="{
                    selectableRange:`${form.startTime? form.startTime+':00' : '00:00:00'}-23:59:00`
                  }"
                />
              </el-col>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane v-if="isWork" label="连续制" name="2">
          <el-form ref="form" :model="form" label-width="130px" :rules="rules">
            <el-form-item label="工作模式名称" prop="name">
              <el-input v-model="form.name" autocomplete="off" />
            </el-form-item>
            <el-form-item label="连续工作天数" prop="day">
              上<el-input v-model="form.workDayNum" placeholder="请输入" style="width: 110px; margin-right: 21px; margin-left: 10px;">
                <span slot="suffix" style="font-weight: 400; color: black;">
                  天
                </span>
              </el-input>
              休<el-input v-model="form.restDayNum" placeholder="请输入" style="width: 110px; margin-right: 21px; margin-left: 10px;">
                <span slot="suffix" style="font-weight: 400; color: black;">
                  天
                </span>
              </el-input>
            </el-form-item>
            <el-form-item label="工作时间" required prop="time">
              <el-col :span="11">
                <el-time-picker
                  v-model="form.workStartMinute1"
                  is-range
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  placeholder="选择时间范围"
                  format="HH:mm"
                  value-format="HH:mm"
                  :picker-options="{
                    selectableRange:`${form.startTime? form.startTime+':00' : '00:00:00'}-23:59:00`
                  }"
                />
              </el-col>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-row type="flex" justify="center">
          <el-button type="primary" @click="submitFn">确 定</el-button>
          <el-button @click="closeFn">取 消</el-button>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getWokeModePageApi, getModeByIdApi, delWorkModeApi } from '@/api/courier'
export default {
  data() {
    return {
      value1: '',
      pickerOptions: {
        format: 'HH:mm'
      },
      activeName: '1',
      isLoading: true,
      isShow: false,
      counts: 0, // 总数量
      params: {
        page: 1,
        pageSize: 20
      },
      tableData: [], // 表格的数据
      form: {},
      selectedDays: [],
      rules: {
        name: [{ required: true, message: '工作模式名称不能为空', trigger: 'blur' }],
        day: [{ required: true, message: '工作模式名称不能为空', trigger: 'blur' }],
        time: [{ required: true, trigger: 'blur' }]
      },
      editId: '',
      isWeek: true, // 礼拜制
      isWork: true // 连续制
    }
  },
  computed: {
    showtitle() {
      return this.editId ? '编辑工作模式' : '新增工作模式'
    }
  },
  created() {
    this.initData()
  },
  methods: {
    // 初始化数据
    async initData() {
      this.isLoading = true
      const res = await getWokeModePageApi(this.params)
      // console.log(res)
      this.tableData = res.items
      this.counts = +res.counts
      // console.log(this.tableData)
      this.isLoading = false
    },
    // 点击编辑按钮
    async editFn(id) {
      this.editId = id
      // console.log(id)
      const res = await getModeByIdApi(id)
      console.log(res)
      // 判断是否是礼拜制
      if (res.workPatternType === 1) {
        // 选中礼拜制单选框
        this.activeName = '1'
        // 关闭连续制tabs
        this.isWork = false
        // 获取周几的复选框
        this.$nextTick(() => {
          this.setSelectedDays()
        })
        this.isShow = true
        this.form = res
      }
      // 判断是否是连续制
      if (res.workPatternType === 2) {
        // 选中连续制单选框
        this.activeName = '2'
        this.isWeek = false
        this.isShow = true
        this.form = res
      }
    },
    // 点击删除按钮
    async delFn(id) {
      console.log(id)
      this.$confirm('确定要删除吗?', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async() => {
        await delWorkModeApi(id)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    // 计算工作时间
    workTime(a, b) {
      return ((b - a) / 60).toFixed(2)
    },
    // 改变每页的条数
    changePageSize(val) {
      this.params.pageSize = val
      this.initData()
    },
    // 改变当前页码
    changePage(val) {
      this.params.page = val
      this.initData()
    },
    // dialog中的复选框
    setSelectedDays() {
      // 先获取对象中所有的键名
      const weekdays = Object.keys(this.form)
      // ['id', 'name', 'workPatternTypeDesc', 'workPatternType', 'workDate', 'userType', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', 'workDayNum', 'restDayNum', 'status', 'workStartMinute1', 'workEndMinute1', 'creater', 'updater', 'isDelete']
      // console.log(weekdays)
      // 对所有键名进行筛选,只要结尾是day的键名
      const one = weekdays.filter((item) => {
        return item.endsWith('day')
      })
      // ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
      // console.log(one)
      // 根据筛选后的键名,从form对象中取值
      const two = one.map((item) => {
        return this.form[item]
      })
      // [1, 1, 1, 1, 1, 1, 1] 或 [1, 0, 0, 0, 0, 0, 0]
      // console.log(two)
      // 根据取值进行判断,值为 1时,复选框选中,返回索引的值+1,为 0时不选中返回null
      const three = two.map((item, index) => item === 1 ? index + 1 : null)
      // [1, 2, 3, 4, 5, 6, 7] 或 [1, null, null, null, null, null, null] 或 [null, 2, null, null, 5, null, 7]
      // console.log(three)
      // 筛选数组,返回值不是null的
      const four = three.filter(item => item !== null)
      // [2, 5, 7]
      // console.log(four)
      // 将最后的结果赋值
      this.selectedDays = four // 数组中有上方label对应的值,就可以选中相应的复选框
      // 下面是 AI写的
      // const weekdays = Object.keys(this.form)
      //   .filter(key => key.endsWith('day'))
      //   .map(key => this.form[key])

      // this.selectedDays = weekdays.map((value, index) => value === 1 ? index + 1 : null).filter(value => value !== null)
    },
    // 提交编辑的数据
    submitFn() {
      // 最后一次校验
      this.$refs.this.form.validate()
    },
    // dialog里面的关闭
    closeFn() {
      this.isWork = true
      this.isWeek = true
      this.isShow = false
      this.form = {}
      this.selectedDays = []
    },
    // 添加工作模式
    addMode() {
      this.isShow = true
    }
  }
}
</script>

<style lang="scss" scoped>
.table-container {
  border: 1px solid #dddddd; /* 设置表格容器的边框 */
}
.custom-table ::v-deep .el-table__header thead th {
  background-color: #f8faff; /* 设置斑马纹的灰色背景色 */
}
.tips {
    margin-left: 130px;
    margin-bottom: 14px;
    color: #bac0cd;
}
</style>
